//
//  SendLocationManager.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 2017/6/26.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "SendLocationManager.h"
#import "LocationManager.h"
#import "UserLocationModel.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <QXDataManager/QXDataManager.h>
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <DriverLoginManager/DriverLoginManager-umbrella.h>
#import <QXYangqilingDriverOfMy/QXYangqilingDriverOfMy-umbrella.h>
#import <QXYueYueModels/QXYueYueModels-umbrella.h>
#import <QXSocketManager/QXSocketManager.h>
#import "SendLocationModel.h"
#import "NotificationNameManager.h"

@interface SendLocationManager ()

/// 定时器
@property(nonatomic , strong) NSTimer *timer;

/// 定时器周期
@property(nonatomic , assign) NSInteger cycleTime;

@property(nonatomic , assign , readwrite) BOOL timerIsWorking;

/// 发送位置信息需要用到的模型,这里的信息必须配置
@property(nonatomic , strong) SendLocationModel *sendLocationModel;

@end

static SendLocationManager *sendLocationManager = nil;
@implementation SendLocationManager

+ (SendLocationManager *)shareManager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sendLocationManager = [SendLocationManager new];
        sendLocationManager.timerIsWorking = NO;
        sendLocationManager.cycleTime = 0;
    });
    
    return sendLocationManager;
}

- (void)startTimer {
    
    if (!self.timerIsWorking) { // 如果定时器没有开启,开启定时器
        
        // 销毁之前的定时器,防止野指针
        if (sendLocationManager.timer == nil) {
            // 获取司机信息
            QXYYUserDriverModel*driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
            if (driverModel == nil) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_LoginOutSuccess object:nil];
                return;
            }
            [[QXSocketManager manager] close];
            [[QXSocketManager manager] loginWithUserId:driverModel.uuid token:driverModel.token isDriver:YES];
            [self configureModelInfoOfNoOrder];
            sendLocationManager.timer = [NSTimer timerWithTimeInterval:15 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:sendLocationManager.timer forMode:NSRunLoopCommonModes];
            [sendLocationManager.timer fire];
            
        }
    }
    self.timerIsWorking = YES;
}

- (void)stopTimer {
    
    if (sendLocationManager.timer != nil) {
        
        [self configiureModelInfoOfOffWorkAndSendLocationInfo];
        
        [sendLocationManager.timer setFireDate:[NSDate distantFuture]];
        [sendLocationManager.timer invalidate];
        sendLocationManager.timer = nil;
    }
    
    self.timerIsWorking = NO;
}


#pragma mark - 定时器 Action
- (void)timerAction:(NSTimer *)timer {
    
    if (sendLocationManager.sendLocationModel == nil) {
        
        return;
    }

    [self sendDriverLocationToServiceWithSendLoactionModel:self.sendLocationModel];
    
    if (self.cycleTime == 0 || self.cycleTime == 4) {
        
        if (self.delegate != nil && [self.delegate respondsToSelector:@selector(refreshAttendanceInfoOfDriver)]) {
            
            [self.delegate refreshAttendanceInfoOfDriver];
        }
        
        if (self.cycleTime == 4) {
            
            self.cycleTime = 0;
        }
        
    }
    
    if (self.cycleTime % 2 == 0) {
        
        if (self.delegate != nil && [self.delegate respondsToSelector:@selector(getWaitingFareWithSendLocationManager:)]) {
            
            [self.delegate getWaitingFareWithSendLocationManager:sendLocationManager];
        }
        
    }
    
    self.cycleTime += 1;
}

#pragma mark - 向服务端发送定位信息
// 注意这里的信息是空驶状态
- (void)sendDriverLocationToServiceWithSendLoactionModel:(SendLocationModel *)model {
    
    if (model == nil) {
        
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // 纬度
    double lat = [LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude;
    // 精度
    double lng = [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude;
    
    // 还未定位成功
    if (lat == 0 || lng == 0 || [LocationManager shareManager].userLocationModel == nil) {
        
        return;
    }
    
    // 角度
    NSString *angle = [NSString stringWithFormat:@"%f" , [LocationManager shareManager].userLocationModel.userLocation.course];
    
    [parameters setValue:@(model.distance) forKey:@"distance"];
    [parameters setValue:@(lat) forKey:@"lat"];
    [parameters setValue:@(lng) forKey:@"lng"];
    [parameters setValue:@"UPLOAD_LOCATION" forKey:@"type"];
    [parameters setValue:@([[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]) forKey:@"driverType"];
    [parameters setValue:[QXDataManager getValueForKey:QXAppId] forKey:@"appid"];
    QXYYUserDriverModel*driver = [QXYYUserDriverModel QXYY_unarchiveObject];
    NSDate *date = [NSDate date];
    NSString *dateStr = [NSString stringWithFormat:@"%.f", [date timeIntervalSince1970] * 1000];
    [parameters setValue:dateStr forKey:@"locationUuid"];
    [parameters setValue:dateStr forKey:@"uploadTime"];
    [parameters setValue:driver.uuid forKey:@"driverUuid"];
    [parameters setValue:@"DRIVER" forKey:@"from"];
    [parameters setValue:driver.uuid forKey:@"clientUuid"];
    [parameters setValue:driver.token forKey:@"token"];
    [parameters setValue:@(model.mileage) forKey:@"mileage"];
    [parameters setValue:@(model.orderStatus) forKey:@"orderStatus"];
    
    // 三级等保 的参数
    // 行政编码
    [parameters setValue:[LocationManager shareManager].userLocationModel.adcode forKey:@"areaCode"];
    // 海拔高度
    [parameters setValue:@([LocationManager shareManager].userLocationModel.altitude) forKey:@"elevation"];
    // 营运状态
    [parameters setValue:@(model.carryPassengerStatus) forKey:@"bizStatus"];
    // 瞬时速度
    [parameters setValue:@([LocationManager shareManager].userLocationModel.speed) forKey:@"speed"];
    // 当前的角度
    [parameters setValue:angle forKey:@"angle"];
    // 订单id
    if (model.orderUuid != nil) {
        
        [parameters setValue:model.orderUuid forKey:@"orderUuid"];
    }else {
        
        [parameters setValue:@"" forKey:@"orderUuid"];
    }
    
    [[QXSocketManager manager] send:parameters];

}

#pragma mark - 配置model
/// 空驶状态的模型配置,出车后需要执行这里的方法,一个订单结束后需要这里再次执行一次
- (void)configureModelInfoOfNoOrder {
    
    SendLocationModel *model = [SendLocationModel new];
    model.orderUuid = @"";
    model.carryPassengerStatus = CarryPassengerStatusDeadhead; // 空驶
    model.distance = 0.0;
    model.mileage = 0.0;
    model.orderStatus = OrderStatusEnumCode_NoOrder;
    
    
    sendLocationManager.sendLocationModel = model;
    
}

/**
 * 空驶状态的模型配置,接到订单后,出发去接乘客
 * distanceOfTwoPoint , 最近两点之间的距离
 * totalDistance , 当前总的行驶里程
 * orderUuid , 订单uuid
 * orderStatusCode , 当前订单的状态
 * 是否需要立即向服务端发送信息
 */
- (void)configureModelInfoOfHasOrderWithTwoPointDistance:(double)distanceOfTwoPoint totalDistace:(double)totalDistance orderUuid:(NSString *)orderUuid orderStatus:(OrderStatusEnumCode)orderStatusCode isSendImmediately:(BOOL)isSendImmediately {
    
    SendLocationModel *model = [SendLocationModel new];
    model.orderUuid = orderUuid;
    model.carryPassengerStatus = CarryPassengerStatusDeadhead; // 空驶
    model.distance = distanceOfTwoPoint;
    model.mileage = totalDistance;
    model.orderStatus = orderStatusCode;
    
    sendLocationManager.sendLocationModel = model;
    
    if (isSendImmediately) {
        
        [self sendDriverLocationToServiceWithSendLoactionModel:sendLocationManager.sendLocationModel];
    }
}

/// 接到订单配置模型信息并发送自身位置信息到服务端,这里接到订单后需要执行一次这个方法
- (void)configureModelInfoOfOrdersAndSendLocationInfoWithOrderUuid:(NSString *)orderUuid {
    
    SendLocationModel *model = [SendLocationModel new];
    model.orderUuid = orderUuid;
    model.carryPassengerStatus = CarryPassengerStatusOrders; // 接到订单
    model.distance = 0.0;
    model.mileage = 0.0;
    model.orderStatus = OrderStatusEnumCode_DriverReceivedOrder_DetermineStroke;
    
    [self sendDriverLocationToServiceWithSendLoactionModel:model];
}

/// 收车后发送一次司机信息到服务端,这个方法需要执行一下
- (void)configiureModelInfoOfOffWorkAndSendLocationInfo {
    
    SendLocationModel *model = [SendLocationModel new];
    model.orderUuid = @"";
    model.carryPassengerStatus = CarryPassengerStatusOutage; // 停运
    model.distance = 0.0;
    model.mileage = 0.0;
    model.orderStatus = OrderStatusEnumCode_NoOrder;
    
    [self sendDriverLocationToServiceWithSendLoactionModel:model];
    
    [[QXSocketManager manager] loginWithUserId:@"" token:@"" isDriver:YES];
    [[QXSocketManager manager] close];
    
}

/// 行程中向服务端发送位置信息,订单开始需要执行一下这里的方法 , 载客状态
- (void)configureModelInfoOfOngoingOrderAndSendLocationInfoWithTwoPointDistance:(double)distanceOfTwoPoint totalDistace:(double)totalDistance orderUuid:(NSString *)orderUuid orderStatus:(OrderStatusEnumCode)orderStatusCode isSendImmediately:(BOOL)isSendImmediately {
    
    SendLocationModel *model = [SendLocationModel new];
    
    model.distance = distanceOfTwoPoint;
    model.mileage = totalDistance;
    model.carryPassengerStatus = CarryPassengerStatusCarryPassenger; // 载客状态
    model.orderUuid = orderUuid;
    model.orderStatus = orderStatusCode;
    
    sendLocationManager.sendLocationModel = model;  // 这里处理的是载客状态
    
    if (isSendImmediately) {
        
        [self sendDriverLocationToServiceWithSendLoactionModel:sendLocationManager.sendLocationModel];
    }
}

@end
